/**
 * Created by Foold on 2014-4-24.
 */
var ztreeId = "#navZtree";
var ztreeObj;
var curNode = null;
var setting = {
    view: {
        addHoverDom: addHoverDom,
        removeHoverDom: removeHoverDom,
        addDiyDom: addDiyDom,
        selectedMulti: false
    },
    edit: {
        enable: true,
        editNameSelectAll: true,
        showRemoveBtn: showRemoveBtn,
        showRenameBtn: showRenameBtn,
        removeTitle: "删除分类",
        renameTitle: "编辑分类",
        drag: {
            autoExpandTrigger: true,
            prev: dropPrev,
            inner: dropInner,
            next: dropNext
        }
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {

        beforeEditName: beforeEditName,
        beforeRemove: beforeRemove,
        beforeRename: beforeRename,
        onRemove: onRemove,
        onRename: onRename,
        beforeDrag: beforeDrag,
        beforeDrop: beforeDrop,
        onDrag: onDrag,
        onDrop: onDrop,
        onClick: ztreeOnClick
    },
    async: {
        enable: true,
        url: "/articlec/ztree",
        autoParam: ["_id=parentId"],
        type: "get"
        //,otherParam: ["timestamp", new Date().getTime()]
    }
};
var areasetting = {
    view: {
        addDiyDom:false,
        addHoverDom: addAreaHoverDom,
        removeHoverDom: removeAreaHoverDom
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    callback:{
        onClick:function(event, treeId, treeNode) {
                var url = '/article/list/1?layout=0';
                curNode = treeNode;
                initSetting(curNode);
                $("#dataTable").load(url, {"articlec.id": treeNode._id});
            }
    }
};
var zNodes = [
    {
        _id: "root",
        name: "网站整体结构",
        isParent: true,
        drag: false
    }
];

var zNodesApp=[
    {
        _id: "apparea",
        name: "应用领域类文章",
        isParent: true,
        drag: false ,
        open:true,
        children:[
            {
                _id:"appareaone",
                name:"航空航天",
                area:"C",
                isParent:false,
                drag:false
            },
            {
                _id:"appareatwo",
                name:"环保",
                area:"C",
                isParent:false,
                drag:false
            },
            {
                _id:"appareathree",
                name:"核电",
                area:"C",
                isParent:false,
                drag:false
            },
            {
                _id:"appareafour",
                name:"船舶",
                area:"C",
                isParent:false,
                drag:false
            }

        ]
    }
];


function ztreeOnClick(event, treeId, treeNode) {
    var url = '/article/list/1?layout=0';
    curNode = treeNode;
    initSetting(curNode);
    $("#dataTable").load(url, {"articlec.id": treeNode._id});
}

function dropPrev(treeId, nodes, targetNode) {
    return true;
}
function dropInner(treeId, nodes, targetNode) {
    return false;
}
function dropNext(treeId, nodes, targetNode) {

    return true;
}
function beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {

    return true;
}
function onDrag(event, treeId, treeNodes) {

}
function onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
    var fromNode = treeNodes[0];
    if (moveType != 'inner') {
        var parent = fromNode.getParentNode();
        if (parent) {
            reSortTreeNodes(parent);
        }
    }

}
function beforeDrag(treeId, treeNodes) {
    return true;
}
function beforeEditName(treeId, treeNode) {
    if (treeNode._id == "root")return false;
    return true;
}
function beforeRemove(treeId, treeNode) {
    if (treeNode._id == "root")return false;
    var zTree = $.fn.zTree.getZTreeObj(treeId);
    zTree.selectNode(treeNode);
    return confirm("确认删除节点" + treeNode.name + " 吗？");
}
function onRemove(event, treeId, treeNode) {
    var parentNode = treeNode.getParentNode();


    $.get('/mainmenu/onlyone', function (menus) {
        var rootmenu = $("<div id='mparent'></div>").append(menus.content);
        //DONE 删除节点并修改菜单
        //log('rootmenu is :');
        // log(rootmenu.html());

        var idz = [];
        //获取自己所在位置

        var self = rootmenu.find("#" + treeNode._id);
        // log('self:');
        // log(self);

        //log('current Node is ');
        // log(treeNode);
        idz.push(treeNode._id);
        //获取自己下的所有子元素
        var children = self.find("ul,li");

        // log('and his children is :');
        // log(children);
        $.each(children, function (i, item) {
            if (item && item.id) {
                idz.push(item.id);
            }
        });

        self.remove();

        // log('after remove :');
        // log(rootmenu.html());
        // log('idz be removed ');
        // log(idz);
        $.post(
                '/articlec/removem/' + treeNode._id
            , {idz: idz, mcontent: rootmenu.html()}
            , function (msg) {
                notify(treeNode.name + "已删除");
                reAsyncNode(parentNode);
            });
    });


}
function beforeRename(treeId, treeNode, newName, isCancel) {
    return true;
}
function onRename(event, treeId, treeNode, isCancel) {
    var parent = treeNode.getParentNode();
    var bean = {name: treeNode.name};
    var myId = treeNode._id;
    $.get('/mainmenu/onlyone', function (menus) {
        var rootmenu = $("<div id='mparent'></div>").append(menus.content);

        var pul = $("ul#" + parent._id + "_parent", rootmenu);
        var clia = $("<a></a>").attr('href', '/child/' + myId).text(treeNode.name);
        var cli = $("<li></li>").attr("id", myId).attr('sort', treeNode.sort).append(clia);
        log(cli[0].outerHTML);
        var tmpul = pul[0];
        var selfjq = rootmenu.find("#" + myId);
        var self = selfjq[0];
        if (tmpul) {

            if (!self) {
                pul.append(cli);
                //log(tmpul.outerHTML);
            } else {
                selfjq.find('a:first').text(treeNode.name);
            }
        } else {
            pul = $("li#" + parent._id, rootmenu);
            if (pul[0]) {
                var tpul = $("<ul></ul>").attr("id", parent._id + "_parent").append(cli);
                pul.append(tpul);
                //log(pul[0].outerHTML);
            }
        }

        //log(rootmenu.html());

        $.post('/articlec/updatem/' + myId,
            {
                menucontent: rootmenu.html(),
                name: treeNode.name
            }
            , function (msg) {
                notify(bean.name + "已修改");
                log(rootmenu.html());
                reAsyncNode(parent);
            });

    });

}
function showRemoveBtn(treeId, treeNode) {
    return treeNode._id != 'root';
}
function showRenameBtn(treeId, treeNode) {
    return treeNode._id != 'root';
}


function addAreaHoverDom(treeId,treeNode){

    if(treeNode._id=='apparea')return false;

    var aObj = $("#" + treeNode.tId + "_a");
    if ($("#diyBtn_"+treeNode._id).length>0) return;
    var editStr = "<span id='diyBtn_space_" +treeNode._id+ "' > "
        + "<button type='button' class='button icon02' style='width:16px;height:16px;border:none' id='diyBtn_" + treeNode._id
        + "' title='"+treeNode.name+"' onfocus='this.blur();'></button></span>";
    aObj.append(editStr);
    var btn = $("#diyBtn_"+treeNode._id);
    if (btn) btn.bind("click", function(){
        var url = "/article/forarea/C/" + treeNode._id+"/"+treeNode.name;
        location.href = url;
        return false;

    });

}
function removeAreaHoverDom(treeId, treeNode) {

    $("#diyBtn_"+treeNode._id).unbind().remove();
    $("#diyBtn_space_" +treeNode._id).unbind().remove();

};

function addHoverDom(treeId, treeNode) {

    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
    var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
        + "' title='新增分类' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_" + treeNode.tId);
    if (btn) btn.bind("click", function () {
        var bean = {
            parentId: treeNode._id,
            name: "新增分类"
        };

        $.post('/articlec/addm', bean, function (result) {
            //log(result);
            ztreeObj.addNodes(treeNode, result);
            reAsyncNode(treeNode);

        });


        return false;
    });

    var editStr = "<span class='button icon02' id='diyBtn_edit_doc" + treeNode._id + "' title='添加文章' onfocus='this.blur();'></span>";
    sObj.append(editStr);
    var btn = $("#diyBtn_edit_doc" + treeNode._id);
    if (btn) btn.bind("click",
        function () {
            var url = "/article/fromac/" + treeNode._id;
            location.href = url;
            return false;
        }
    );
}

function addDiyDom(treeId, treeNode) {
    return false;

}


function removeHoverDom(treeId, treeNode) {
    $("#addBtn_" + treeNode.tId).unbind().remove();
    $("#diyBtn_edit_doc" + treeNode._id).unbind().remove();
    $("#diyBtn_view_doc" + treeNode._id).unbind().remove();

};


function reSortTreeNodes(parent) {
    var cnodes = parent.children;
    var bean = {};

    $.get('/mainmenu/onlyone', function (menus) {
        var rootmenu = $("<div id='mparent'></div>").append(menus.content);
        for (var c = 0; c < cnodes.length; c++) {
            var child = cnodes[c];
            bean[child._id] = {'sort': c};
            $("li#" + child._id, rootmenu).attr("sort", c);
        }

        var sdata = {
            bean: bean,
            menucontent: rootmenu.html()
        };

        $.post('/articlec/updates/sort', sdata, function (rst) {
            info("排序更新完成");
        });

    });


}

function reAsyncNode(treeNode) {
    ztreeObj.reAsyncChildNodes(treeNode, "refresh");
    expandNode(treeNode);
}

function expandNode(treeNode) {
    ztreeObj.expandNode(treeNode);
}


$(function () {

    ztreeObj = $.fn.zTree.init($(ztreeId), setting, zNodes);
    $.fn.zTree.init($("#apptree"), areasetting, zNodesApp);

    var nodes = ztreeObj.getNodes();
    expandNode(nodes[0]);
});

function initSetting(node) {
    if(node.area=='C')return;
    $("#addr").val(node.url);
    $("#curArea").text(node.area ? node.area : 'N');
}

function saveAddr(event) {
    if (!curNode )return;
    var arcid = curNode._id;

    $(event.target).prop("disabled", true);
    $.post('/articlec/update/' + arcid, {"url": $("#addr").val()}, function (rst) {
        //log(rst);
        info("连接设置成功");
        $(event.target).prop("disabled", false);
    });
}

function setArea(area) {
    if (!curNode)return;
    var arcid = curNode._id;

    $(event.target).prop("disabled", true);
    $.post('/articlec/update/area/' + arcid, {"area": area}, function (rst) {
        //log(rst);
        info("设置成功");
        $(event.target).removeProp('disabled');
    });
}